﻿using Newtonsoft.Json.Linq;
using SuperiorCommon;
using SuperiorModel;
using SuperiorShopBussinessService;
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace H5.SuperiorShop.Controllers
{
    public class LoginController : BaseController
    {
        private readonly IUserService _IUserService;
        private readonly IShopAppService _IShopAppService;

        public LoginController(IUserService IUserService, IShopAppService IShopAppService)
        {
            _IUserService = IUserService;
            _IShopAppService = IShopAppService;

        }
        protected override void Dispose(bool disposing)
        {
            this._IUserService.Dispose();
            this._IShopAppService.Dispose();
            base.Dispose(disposing);
        }
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {       
            string code = Request["code"];
            string state = Request["state"];
            var appid = ConfigSettings.Instance.APPID;
            var secret = ConfigSettings.Instance.APP_Secret;
            if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
            {
                int spid = 0;
                if (!int.TryParse(SecretClass.DecryptQueryString(state), out spid))
                {
                }
                if (spid == 0)
                {
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("请不要随意改变网站参数", Encoding.UTF8));
                    return new EmptyResult();
                }
                //通过code换取网页授权access_token
                string tokens = WeiXinHelper.GetToken(appid, secret, code);
                try
                {
                    JObject jo = JObject.Parse(tokens);
                    string openid = jo["openid"].ToString();
                    string access_token = jo["access_token"].ToString();

                    if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(access_token))
                    {
                        LogManger.Instance.WriteLog("openid:"+openid+"-------token:"+access_token);
                        //读取用户最新信息
                        string jsonstr = WeiXinHelper.GetUserInfo(access_token, openid);
                        LogManger.Instance.WriteLog("获取USERiNFO" + jsonstr);
                        Newtonsoft.Json.Linq.JObject joUser = Newtonsoft.Json.Linq.JObject.Parse(jsonstr);
                        var model = new Api_WxUserLoginCriteria();
                        model.Spid = spid.ToString();
                        model.HeadImgUrl = joUser["headimgurl"].ToString();
                        model.Sex = int.Parse(joUser["sex"].ToString());
                        model.NickName = joUser["nickname"].ToString();
                        model.AppType = 2;
                        model.OpenId = openid;
                        //注册或者更新用户
                        var res = _IUserService.Api_WxUserLoginOrRegister(model);
                        if (string.IsNullOrEmpty(res.Token))
                        {
                            Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("注册或更新用户失败", Encoding.UTF8));
                            return new EmptyResult();
                        }
                        //不能和api共用一个模型，因为stateServer存储session必须可序列化，而接口可序列化返回得不对，暂时分开
                        var userModel = new WxUserLoginResutModel(res);
                        LogManger.Instance.WriteLog("USERMODEL:"+userModel.ToJson());
                        //更新session,跳转页面
                        SessionManager.SetSession(SessionKey.H5UserKey, userModel, state);
                        var jumpUrl = CookieHelper.GetCookieValue("LOGINJUMPURL");
                        Response.Redirect(jumpUrl, false);
                        return new EmptyResult();
                    }
                    else
                    {
                        Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("获取微信信息失败", Encoding.UTF8));
                        return new EmptyResult();
                    }
                }
                catch (Exception ex)
                {
                    LogManger.Instance.WriteLog("获取获取access_token异常:"+ex.ToString());
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("获取access_token异常", Encoding.UTF8));
                    return new EmptyResult();
                }
                
            }
            else
            {
                var spid = base.CheckSpid();
                if (spid == 0)
                {
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("请不要随意改变网站参数", Encoding.UTF8));
                    return new EmptyResult();
                }
                //发起请求
                var redirect = ConfigSettings.Instance.WebHost + "Login/Login";
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + HttpUtility.UrlEncode(redirect, Encoding.UTF8) + "&response_type=code&scope=snsapi_userinfo&state=" + SecretClass.EncryptQueryString(spid.ToString()) + "#wechat_redirect";
                Response.Redirect(url);
                //以下代码为测试，跳过微信浏览器授权
                // http://wx.youyue1118.com/?spid=ABB28D5708B22916&said=138CE358CC93B436
                //var userSessionModel = _IUserService.GetUserSessionModel(9);
                //var spid = "ABB28D5708B22916";
                //if (!string.IsNullOrEmpty(userSessionModel.Id))
                //{
                //    SessionManager.SetSession(SessionKey.H5UserKey + spid, userSessionModel);
                //    var jumpUrl = CookieHelper.GetCookieValue("LOGINJUMPURL");
                //    Response.Redirect(jumpUrl, false);
                //    return new EmptyResult();
                //}
                //else
                //{
                //    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("本地调试登录异常", Encoding.UTF8));

                //}
                return new EmptyResult();
            }
        }
    }
}